package com.dominator.utils.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShortUrlUtil {
    private static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);

    public static int TIMEOUT = 30 * 1000;
    public static String ENCODING = "UTF-8";

    /**
     * JSON  
     * get value by key  
     * @param replyText
     * @param key
     * @return
     */
    private static String getValueByKey_JSON(String replyText, String key){
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node;
        String tinyUrl = null;
        try {
            node = mapper.readTree(replyText);
            tinyUrl = node.get(key).asText();
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }

        return tinyUrl;
    }



    /**
     * 通过HttpConnection 获取返回的字符串  
     * @param connection
     * @return
     * @throws IOException
     */
    private static String getResponseStr(HttpURLConnection connection)
            throws IOException{
        StringBuffer result = new StringBuffer();
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, ENCODING));
            String inputLine = "";
            while ((inputLine = reader.readLine()) != null) {
                result.append(inputLine);
            }
        }
        return String.valueOf(result);
    }


    /**‘  
     * 百度短链接接口  无法处理不知名网站，会安全识别报错  
     * @param args
     */
    public static void main(String[] args) {
        try{
            URL url = new URL("http://dwz.cn/create.php");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //POST Request Define:     
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(TIMEOUT);
            connection.setRequestMethod("POST");
            String longUrl = "url=www.sina.com";

            connection.getOutputStream().write(longUrl.getBytes());
            connection.connect();

            String responseStr = getResponseStr(connection);
            System.out.println("response string: " + responseStr);

            String tinyUrl = getValueByKey_JSON(responseStr, "tinyurl");
            System.out.println("tinyurl: " + tinyUrl);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public static String getShortUrl(String longUrl){
        String tinyUrl = "";
        try{
            URL url = new URL("http://dwz.cn/create.php");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //POST Request Define:
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(TIMEOUT);
            connection.setRequestMethod("POST");

            connection.getOutputStream().write(longUrl.getBytes());
            connection.connect();

            String responseStr = getResponseStr(connection);
            System.out.println("response string: " + responseStr);

            tinyUrl = getValueByKey_JSON(responseStr, "tinyurl");
            System.out.println("tinyurl: " + tinyUrl);
        }catch(IOException e){
            e.printStackTrace();
        }
        return  tinyUrl;
    }

}  
